<template>
  <div>
    <scroller class="scroller border-bottom mb-2"
              :show-scrollbar="false"
              scroll-direction="horizontal">
      <text class="tab-text"
            v-for="(cate, index) in categories"
            :class="[cateIndex===index?'tab-text-active':'']"
            :key="index"
            @click="onCateSelect(cate, index)">{{cate.name}}</text>
    </scroller>

    <div class="bg-white flex-row">
      <text class="type-text"
            v-for="(type, index) in types"
            :class="[typeIndex===index?'type-text-active':'']"
            :key="index"
            @click="onTypeSelect(type, index)">{{type}}</text>
    </div>

    <div class="bg-white p-2">
      <text class="p-1 text-center text-lg">{{label}}</text>
      <text class="text-muted small text-center mb-2">(点击可查看具体数值, 0表示无数据)</text>
    </div>

    <bmchart ref="chart"
             :options="$format(options)"
             style="width:750; height:560;"></bmchart>
  </div>
</template>
<script>
export default {
  components: {},
  props: {},
  data() {
    return {
      categories: [
        {
          name: '活鸡',
          code: '100604005000',
          isFetch: false,
          unit: '',
          day: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          },
          month: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          },
          quarter: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          },
          year: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          }
        },
        {
          name: '鸡蛋',
          code: '100605000000',
          isFetch: false,
          unit: '',
          day: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          },
          month: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          },
          quarter: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          },
          year: {
            legend: [],
            xData: [],
            seriesDataA: [],
            seriesDataB: []
          }
        },
      ],
      cateIndex: 0,
      types: ['近7年', '近12月', '近4季度', '近30天'],
      typeIndex: 0,
      options: {
        color: ['#42bd56'],
        backgroundColor: '#ffffff',
        title: {
          text: '',
          left: 'center',
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: '4%',
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: [],
            axisTick: { alignWithLabel: true }
          }
        ],
        yAxis: [
          { type: 'value' }
        ],
        series: [
          {
            name: '',
            type: 'bar',
            barWidth: '60%',
            data: []
          }
        ]
      },
      colors: ['#8ec6ad', '#ffe']
    }
  },
  computed: {
    label() {
      return this.categories[this.cateIndex].name + this.types[this.typeIndex] + '均价趋势'
    }
  },
  watch: {},
  created() {
    this.getMarket()
  },
  methods: {
    onCateSelect(cate, index) {
      this.cateIndex = index
      this.getMarket()
    },
    onTypeSelect(type, index) {
      this.typeIndex = index
      this.setOption()
    },
    getMarket() {
      const cate = this.categories[this.cateIndex]
      if (cate.isFetch) {
        this.setOption()
        return
      }
      this.$notice.loading.show()
      this.$api.getData({
        server: 'industrial_db',
        table: 'product_market_statics',
        params: {
          'category_code.eq': cate.code
        },
        errorMsg: '获取市场行情数据失败'
      }).then(res => {
        cate.isFetch = true
        if (!(res && res.length)) {
          this.$notice.toast({ messge: '无该产品的市场行情数据' })
        }
        const data = res[0]
        cate.unit = data.unit || ''
        try {
          const dataDay = JSON.parse(data.day_json)
          const dataMonth = JSON.parse(data.month_json)
          const dataQuarter = JSON.parse(data.quarter_json)
          const dataYear = JSON.parse(data.year_json)

          // 近7年
          const year = new Date().getFullYear()
          const yearList = []
          for (let i = year - 6; i <= year; i++) {
            yearList.push(i)
          }
          this.convertData('year', dataYear, yearList, '年')

          // 近4个季度
          const quarterList = []
          for (let i = 1; i <= 4; i++) {
            quarterList.push(i)
          }
          this.convertData('quarter', dataQuarter, quarterList, '季度')

          // 近一年
          const monthList = []
          for (let i = 1; i <= 12; i++) {
            monthList.push(i)
          }
          this.convertData('month', dataMonth, monthList, '月')

          // 近30天
          const dayList = []
          if (dataDay && dataDay.data && dataDay.data.length) {
            const dd = dataDay.data[0].data || []
            for (const ds of dd) {
              if (ds && ds.length > 1) {
                dayList.push(ds[1])
              }
            }
          }
          this.convertData('day', dataDay, dayList, '')

          this.setOption()
        } catch (err) {
          console.log(err)
        }
      }).finally(() => {
        this.$notice.loading.hide()
      })
    },
    convertData(type, data, list, label) {
      let legend = []
      const xData = []
      const aData = []
      const bData = []
      if (data && data.data && data.data.length > 1) {
        legend = [data.data[0].serieName, data.data[1].serieName]
        const dataA = data.data[0].data || []
        const dataB = data.data[1].data || []
        for (const i of list) {
          xData.push(`${i}${label}`)
          let ad = '0'
          let bd = '0'
          for (let j = 0; j < dataA.length; j++) {
            const a = dataA[j]
            if (a && a.length > 1 && (a[1] === i || Number(a[1]) === Number(i))) {
              ad = a[0]
              dataA.splice(j, 1)
            }
          }
          for (let k = 0; k < dataB.length; k++) {
            const b = dataB[k]
            if (b && b.length > 1 && (b[1] === i || Number(b[1]) === Number(i))) {
              bd = b[0]
              dataB.splice(k, 1)
            }
          }
          aData.push(ad)
          bData.push(bd)
        }
      }
      this.categories[this.cateIndex][type].legend = legend
      this.categories[this.cateIndex][type].xData = xData
      this.categories[this.cateIndex][type].seriesDataA = aData
      this.categories[this.cateIndex][type].seriesDataB = bData
    },
    setOption() {
      const indexMap = {
        0: 'year',
        1: 'month',
        2: 'quarter',
        3: 'day',
      }
      const data = this.categories[this.cateIndex][indexMap[this.typeIndex]]
      this.options = {
        backgroundColor: '#ffffff',
        title: {
          show: false,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          top: 0,
          data: data.legend || []
        },
        xAxis: [{
          type: 'category',
          data: data.xData || [],
          boundaryGap: false,
          // axisLabel: {
          //   formatter: v => formatterXLength(v, 5)
          // }
        }],
        yAxis: [{
          type: 'value',
          name: this.categories[this.cateIndex].unit
        }],
        series: [{
          name: data.legend ? data.legend[0] : '',
          type: 'line',
          data: data.seriesDataA || [],
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1, colorStops: this.colors.map((color, index) => {
                  return { offset: index / this.colors.length, color }
                })
              }
            }
          }
        }, {
          name: data.legend ? data.legend[1] : '',
          type: 'line',
          data: data.seriesDataB || [],
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1, colorStops: this.colors.map((color, index) => {
                  return { offset: index / this.colors.length, color }
                })
              }
            }
          }
        }]
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.text-muted {
  color: #999;
}
.text-gray {
  color: #666;
}
.bg-white {
  background-color: #fff;
}
.small {
  font-size: 26px;
}
.mb-1 {
  margin-bottom: 10px;
}
.mb-2 {
  margin-bottom: 20px;
}
.mb-3 {
  margin-bottom: 30px;
}
.p-3 {
  padding: 30px;
}
.p-2 {
  padding: 20px;
}
.p-1 {
  padding: 10px;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.text-center {
  text-align: center;
}
.align-center {
  align-items: center;
}
.border-bottom {
  border-bottom-color: $border-color;
  border-bottom-width: 1px;
}

.text-lg {
  font-size: 34px;
}

.scroller {
  padding: 15px;
  background-color: #fff;
  flex-direction: row;
  height: 100px;
}
.tab-text {
  padding-left: 60px;
  padding-right: 60px;
  margin-right: 30px;
  height: 70px;
  line-height: 70px;
  align-items: center;
  border-radius: 35px;
  border-style: solid;
  border-width: 1px;
  border-color: $accent;
}
.tab-text-active {
  color: #fff;
  background-color: $accent-light;
}
.type-text {
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 10px;
  margin-right: 10px;
  padding: 10px;
  border-style: solid;
  border-width: 1px;
  border-color: $border-color;
  text-align: center;
  flex: 1;
  color: #666;
}
.type-text-active {
  color: #fff;
  background-color: $primary-light;
}
</style>
